package com.actions;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


import com.DAO.NoticeDAO;
import com.DAO.UserDAO;
import com.beans.*;

public class LoginAction extends org.apache.struts.action.Action{

	private final static String SUCCESS = "success";
	private final static String FAILURE = "failure";
    
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
    	
    	LoginForm loginForm = (LoginForm)form;
    	HttpSession session=request.getSession();
    	String loginId=loginForm.getUsername().trim();
    	String password=loginForm.getPassword();
    	
    	
    	UserDAO userDAO=new UserDAO();    	
    	UserForm userForm=userDAO.getUserInfo(loginId, password);
    	  	
    	System.out.println(userForm);
    	
    	// Delete post which has Expired
    	
    	try{
    	NoticeDAO noticeDAO=new NoticeDAO();
    	ArrayList<NoticeForm>  noticelist =noticeDAO.get();
    	
       	for(NoticeForm noticeForm:noticelist){
    		
    		String expdate=noticeForm.getExpirationDate();
    		    		
    		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			java.util.Date d=new java.util.Date();			
			String currentDate = dateFormat.format(d);
			
			if(expdate.equals(currentDate)){
				
				  noticeDAO.delete(noticeForm.getNoticeId());
				  
			}
			
			System.out.println("Expiration date...."+expdate+"......"+currentDate);
    		
    	}
    	
    	}
    	
    	catch(Exception e){
    		
    		   System.out.println("Notice not Found");
    	}
    	if(userForm.getIsAdmin()!=null) {
    		
    	String isAdmin=userForm.getIsAdmin();
    	String userId=userForm.getUserId();
    	String name=userForm.getUserName();
    	
    	
    	
    	
    	
    	if(isAdmin.equals("T"))
    	{
    		session.setAttribute("user_type","admin");
    		session.setAttribute("userid",userId);
    		session.setAttribute("name",name);
    		return mapping.findForward(SUCCESS);
    		
    	}
    	else 
    	{
    		session.setAttribute("user_type","user");
    		session.setAttribute("userid",userId);
    		session.setAttribute("name",name);
    		return mapping.findForward(SUCCESS);    		
    	}
    	
    	}
    	
    	
    	  		
		return mapping.findForward(FAILURE);
		
	} 
}
